package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class ProxyAction extends AxdrType {
    private ByteBuffer dataCode = null;
    private OMD omd = null;
    private Data param = null;

    public ProxyAction() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = ByteBuffer.wrap(dataCode);
    }

    public void setAll(OMD omd, Data param) {
        this.omd = omd;
        this.param = param;
    }

    public void setOmd(OMD omd) {
        this.omd = omd;
    }

    public void setParam(Data param) {
        this.param = param;
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.omd = new OMD();
        codeLength += this.omd.decode(input);
        this.param = new Data();
        codeLength += this.param.decode(input);
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength = 0;
        if (this.dataCode != null) {
            byte[] data = this.dataCode.array();
            codeLength = data.length;
            for (int i = data.length - 1; i >= 0; i--) {
                output.write(data[i]);
            }
        } else {
            if (this.param != null && this.omd != null) {
                codeLength += this.param.encode(output);
                codeLength += this.omd.encode(output);
            } else {
                throw new RuntimeException("param || omd is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = ByteBuffer.wrap(revOStream.getArray());
    }

    @Override
    public String toString() {
        if (this.param != null && this.omd != null) {
            return "sequence: {" + "omd: " + this.omd + ", param: " + this.param + "}";
        } else {
            return "param || omd is null";
        }
    }
}



